<template>
  <div class="aui-wrapper aui-page__login">
    <div class="aui-content__wrapper">
      <main class="aui-content">
        <div class="login-header">
          <h2 class="login-brand">{{ $t('brand.lg') }}</h2>
        </div>
        <div class="login-body">
          <!--<h3 class="login-title">{{ $t('login.title') }}</h3>-->
          <el-form
            :model="dataForm"
            :rules="dataRule"
            ref="dataForm"
            :validate-on-rule-change="false"
            @keyup.enter.native="dataFormSubmitHandle()"
            status-icon>
            <el-form-item prop="mobile">
              <el-input
                type="number"
                v-model="dataForm.mobile"
                :placeholder="$t('login.telephone')">
                <span
                  slot="prefix"
                  class="el-input__icon">
                  <svg
                    class="icon-svg"
                    aria-hidden="true"><use xlink:href="#icon-phone"/></svg>
                </span>
              </el-input>
            </el-form-item>

            <el-form-item prop="captcha">
              <el-row :gutter="20">
                <el-col :span="14">
                  <el-input
                    v-model="dataForm.captcha"
                    :placeholder="$t('login.captcha')">
                    <span
                      slot="prefix"
                      class="el-input__icon">
                      <svg
                        class="icon-svg"
                        aria-hidden="true"><use xlink:href="#icon-safetycertificate"/></svg>
                    </span>
                  </el-input>
                </el-col>
                <el-col
                  :span="10"
                  class="login-captcha">
                  <img
                    :src="captchaPath"
                    @click="getCaptcha()">
                </el-col>
              </el-row>
            </el-form-item>

            <el-form-item prop="smsCode">
              <el-row :gutter="20">
                <el-col :span="14">
                  <el-input
                    type="number"
                    v-model="dataForm.smsCode"
                    :placeholder="$t('login.smsCode')">
                    <span
                      slot="prefix"
                      class="el-input__icon">
                      <svg
                        class="icon-svg"
                        aria-hidden="true"><use xlink:href="#icon-safetycertificate"/></svg>
                    </span>
                  </el-input>
                </el-col>
                <el-col
                  :span="10"
                  class="login-captcha">
                  <el-button
                    type="primary"
                    style="width: 100%"
                    :loading="button.loading"
                    :disabled="button.disabled"
                    @click="sendSms()">{{ button.text }}</el-button>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item style="margin-bottom: 0">
              <el-button
                type="primary"
                @click="dataFormSubmitHandle()"
                class="w-percent-100"
                v-loading="requesting">{{ $t('login.title') }}</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="login-footer">
          <!--<p>{{ $t('login.demo') }}</p>-->
          <p><a
            href="#"
            target="_blank"/>2019 © {{ $t('login.copyright') }}</p>
        </div>
      </main>
    </div>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import debounce from 'lodash/debounce'
import { messages } from '@/i18n'
import { getUUID } from '@/utils'
const COUNT_DOWN = 60
const SMS_BUTTON_TEXT = '发送短信'
const TELEPHONE_TEXT = '请输入合法的11位手机号'

export default {
  data () {
    return {
      requesting: false,
      i18nMessages: messages,
      captchaPath: '',
      tabMapOptions: this.initTabMapOptions(),
      dataForm: {
        mobile: '',
        uuid: '',
        captcha: '',
        smsCode: ''
      },
      tabIndex: 1,
      button: {
        loading: false,
        disabled: false,
        text: SMS_BUTTON_TEXT
      },
      time: COUNT_DOWN
    }
  },
  computed: {
    dataRule () {
      const keys = [['username', 'password'], ['mobile', 'smsCode']]
      const rule = [{ required: true, message: this.$t('validate.required'), trigger: 'blur' }]
      let buffer = {}

      keys[this.tabIndex].map((key) => {
        if (key === 'mobile') {
          const _rule = rule.concat()
          _rule.push({ min: 11, max: 11, message: TELEPHONE_TEXT, trigger: 'blur' })
          buffer[key] = _rule
          console.log(buffer[key])
        } else {
          buffer[key] = rule
        }
      })

      buffer['captcha'] = rule.concat()

      return buffer
      // return {
      //   username: [
      //     { required: true, message: this.$t('validate.required'), trigger: 'blur' }
      //   ],
      //   mobile: [
      //     { required: true, message: this.$t('validate.required'), trigger: 'blur' }
      //   ],
      //   password: [
      //     { required: true, message: this.$t('validate.required'), trigger: 'blur' }
      //   ],
      //   captcha: [
      //     { required: true, message: this.$t('validate.required'), trigger: 'blur' }
      //   ],
      //   smsCode: [
      //     { required: true, message: this.$t('validate.required'), trigger: 'blur' }
      //   ]
      // }
    }
  },
  created () {
    this.getCaptcha()
    this.getLastTimeLoginMobile()
  },
  methods: {
    initTabMapOptions () {
      const tabs = [
        { label: '密码登录' },
        { label: '短信登录' }
      ]
      const buffer = []
      tabs.forEach((item, index) => {
        const _item = Object.assign({}, item, { key: `${index}` })
        buffer.push(_item)
      })
      return buffer
    },
    getLastTimeLoginMobile () {
      let mobile = localStorage.getItem('___Midea_admin_login_mobile')
      if (mobile && mobile.length > 0) {
        this.dataForm.mobile = mobile
      }
    },
    // 获取验证码
    getCaptcha () {
      this.dataForm.uuid = getUUID()
      this.captchaPath = `${window.SITE_CONFIG['apiURL']}/captcha?uuid=${this.dataForm.uuid}`
    },
    sendSms () {
      let { dataForm } = this
      if (!dataForm.mobile || dataForm.mobile.length !== 11) {
        this.$message({
          message: TELEPHONE_TEXT,
          type: 'warning'
        })
        return
      }

      if (!dataForm.captcha) {
        this.$message({
          message: '请先输入验证码',
          type: 'warning'
        })
        return
      }

      let { button } = this
      button.loading = true
      button.text = '发送中'
      this.$http.get('/sms_code', { params: this.dataForm }).then(({ data: res }) => {
        button.loading = false
        if (res.code) {
          button.text = SMS_BUTTON_TEXT
          return this.$message.error(res.msg)
        }
        this.countdown()
      })
    },
    countdown () {
      let { button } = this
      // button.loading = true
      button.disabled = true
      let timer = window.setInterval(() => {
        button.text = `(${this.time}秒) 后重新发送`
        --this.time
        if (this.time < 0) {
          this.time = COUNT_DOWN
          button.text = SMS_BUTTON_TEXT
          button.disabled = false
          window.clearInterval(timer)
        }
      }, 1000)
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      if (this.requesting) {
        return
      }
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.requesting = true
        const url = parseInt(this.tabIndex) ? '/login_sms' : '/login'
        this.$http.post(url, this.dataForm).then(({ data: res }) => {
          if (res.code !== 0) {
            this.getCaptcha()
            return this.$message.error(res.msg)
          }
          Cookies.set('token', res.data.token)

          // Feature:save to localstorage of current login mobile, and if need to login next time, will automatically refill in input
          localStorage.setItem('___Midea_admin_login_mobile', this.dataForm.mobile)
          this.$router.replace({ name: 'home' })
        }).catch(() => {}).finally(() => {
          this.requesting = false
        })
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>
